package com.cx.mall.cart.service.impl;

import com.cx.mall.cart.mapper.CartMapper;
import com.cx.mall.common.model.cart.Cart;
import com.cx.mall.cart.service.ICartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartServiceImpl implements ICartService {
    @Autowired
    private CartMapper cartMapper;
    @Override
    public void add(Cart cart) {
        //如果购物车中商品已存在，读取数量，并删除
        if(cartMapper.existsById(cart.get_id())){
            Cart obj = cartMapper.findById(cart.get_id()).get();
            cart.setNum(obj.getNum() + cart.getNum());
            cartMapper.deleteById(cart.get_id());
        }
        //增加
        cartMapper.save(cart);
    }

    @Override
    public List<Cart> list(String userId) {
        //查询条件
        Cart cart = new Cart();
        cart.setUserId(userId);
        return cartMapper.findAll(Example.of(cart), Sort.by(Sort.Direction.DESC,"createTime"));
    }

    @Override
    public void removeById(String id) {
        cartMapper.deleteById(id);
    }

    @Override
    public void removeByIds(List<String> ids) {
        cartMapper.deleteAllById(ids);
    }
}
